package com.fwmagic.webmagic;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.io.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 爬取兴趣e族博客（csdn）
 */
public class FwBlogPageProcessor implements PageProcessor {

    private Site site = Site.me().setDomain("simplelife.blog.51cto.com").setRetryTimes(3).setSleepTime(1000);

    //详情页表达式
    private static final String URL_PATTERN = "http://simplelife\\.blog\\.51cto\\.com/9954761/\\d+";

    private final AtomicLong count = new AtomicLong(0);

    @Override
    public void process(Page page) {

        //取详情页数据
        if(page.getUrl().regex(URL_PATTERN).match()){
            page.putField("标题",page.getHtml().xpath("//div[@class='showTitle']/text()"));
            if(page.getResultItems().get("标题")==null){
                page.setSkip(true);
            }else{
                page.putField("地址",page.getUrl());
                page.putField("发布时间",page.getHtml().xpath("//span[@class='artTime']/text()"));
                count.incrementAndGet();//+1
                File text = new File("F:/blog.txt");
                try {
                    FileWriter output = new FileWriter(new File("F:/blog.txt"), true);
                    output.write("标题:"+page.getResultItems().get("标题")+"\r\n");
                    output.write("地址:"+page.getResultItems().get("地址")+"\r\n");
                    output.write("发布时间:"+page.getResultItems().get("发布时间")+"\r\n");
                    output.write("======================================================="+"\r\n");
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {

                }
                System.out.println("==========【兴趣e族】共抓取到"+count+"条有效数据============");
            }
        }else{
            //发现详情页
            page.addTargetRequests(page.getHtml().css("div.blogList").links().regex(".*/\\d+/\\d+").all());
            //发现下一页
            page.addTargetRequests(page.getHtml().css("div.pages").links().regex(".*/\\w+/p-\\w+").all());
        }
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new FwBlogPageProcessor()).addUrl("http://simplelife.blog.51cto.com/9954761/p-1").thread(3).run();
    }
}
